package com.demo.weixin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.demo.api.CheckJs;
import com.demo.api.MediaApi;
import com.demo.index.WxInterceptor;
import com.demo.mb.WxMbsx;
import com.demo.util.AmrToMp3;
import com.demo.util.PropertiesHelper;
import com.demo.util.Upload;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheKit;

@ClearInterceptor
public class WxContentController extends Controller {
	private static String url = "";
	private static String AppId = "";

	static {
		Properties r = PropertiesHelper.loadProperty("/weixin.properties");
		if (!r.isEmpty()) {
			try {
				url = r.getProperty("wxmediaUrl");
				AppId = r.getProperty("AppId");

				if (!url.endsWith("/"))
					url = url + "/";
			} catch (Exception e) {
				Logger.getLogger(Upload.class).error("无法读取参数", e);
			}
		} else {
			Logger.getLogger(Upload.class).error("无法读取 weixin.properties");
		}
	}


	public void index() {
		String type = "";
		String id = getPara("id");
		String aa = getPara(0);
		String  from=getPara("from");
		if (StringKit.notBlank(aa)) {
			id = aa;
			WxContent cont = WxContent.dao.findFirst("select yds from wx_content  where  id='" + id+ "'");
			String yds = cont.getStr("yds");
			if (!StringKit.notBlank(yds)) {
				yds = "0";
			}
			int s = Integer.parseInt(yds) + 1;
			Db.update(" update wx_content set yds=" + s + "  where id ='" + id+ "'");
		}
		// from =user 则为用户自己制作可以修改 如果不是 则为分享访问
		String pic = "";
		String title = "";
		String descContent="";
		List<Record> newlist = WxContent.dao.findAlls("       id=  '" + id+ "'", "");
		setAttr("newlist", newlist);
		setAttr("url", url);
		String gkzt="";
		setAttr("AppId", AppId);
		setAttr("id", id);
		if (newlist.size() > 0) {
			type = newlist.get(0).get("type");
			title = newlist.get(0).get("title");
			gkzt = newlist.get(0).get("gkzt");
			descContent=newlist.get(0).get("content");
			descContent=getAbStract(descContent);
			if (descContent.length()>20){
				descContent=descContent.substring(0,20)+"...";
			}
			if (newlist.get(0).get("picurl") != null) {
				if (url.endsWith("/")) {
					pic = url+ newlist.get(0).get("picurl");
				}
			}
		}
		setAttr("gkzt", gkzt);
		setAttr("pic", pic);
		setAttr("title", title);
		setAttr("descContent", descContent);
		if (StringKit.notBlank(aa)) {
			setAttr("argu","none");
		} else {
			if (StringKit.notBlank(from) && from.equals("user") )
			setAttr("argu","edit");
		}
		String urls="";
		List<Record> mblist = Db.find("Select *  from wx_mb where id ='"+type+"'  order by dsporder");
		List<Record> mbtypelist = new ArrayList<Record>();
		mbtypelist = CacheKit.get("typelist", "typelist" + type);
		if (mbtypelist == null) {
			mbtypelist = Db.find("Select *  from wx_mbsx where  lbid ='"+ type+ "'  order by dsporder");
			CacheKit.put("mbtypelist", "mbtypelist" + type, mbtypelist);
		}
		urls=mblist.get(0).get("mburl");
		String bjzt=mblist.get(0).get("bjzt");
		if (urls != null && !urls.substring(0, 1).equals("/")) {
			urls = "/" + urls;
		}
		setAttr("bjzt","bjzt");
		setAttr("mbtypelist",mbtypelist);
		setAttr("mblist",mblist);
		render("/WEB-INF/view/weixin/temp" + urls);

	}

	public void saves() {
		render("/WEB-INF/view/weixin/temp/view0.html");

	}

	public void gk() {
		String id = getPara("id");
		String gkzt = getPara("gkzt");
		Db.update(" update  wx_content  set  gkzt=" + gkzt + " where id ='"
				+ id + "'  ");
		renderJson(id);
	}

	public void getTemp() {
		String type = getPara("id");
		List<Record> mblist = Db.find("Select *  from wx_mb where id ='" + type
				+ "'  order by dsporder");
		String urls = "";
		if (mblist.size() > 0) {
			urls = mblist.get(0).get("mburl");
			String bjzt = mblist.get(0).get("bjzt");
			if (urls != null && !urls.substring(0, 1).equals("/")) {
				urls = "/" + urls;
			}
			setAttr("bjzt", "bjzt");
			setAttr("mblist", mblist);
		}
		render("/WEB-INF/view/weixin/temp" + urls);
	}

	/**
	 * 访问模板
	 */
	public void views() {
		String type = getPara("type");
		String title = getPara("title");
		String fromuser = getPara("fromuser");
		String content = getPara("content");
		String pic = getPara("pic");
		setAttr("type", type);
		setAttr("title", title);
		setAttr("fromuser", fromuser);
		setAttr("content", content);
		setAttr("pic", pic);
		if (type.equals("1")) {
			render("/WEB-INF/view/weixin/temp/view0.html");
		} else if (type.equals("2")) {
			render("/WEB-INF/view/weixin/temp/view1.html");
		} else if (type.equals("3")) {
			render("/WEB-INF/view/weixin/temp/view2.html");
		} else {
			render("/WEB-INF/view/weixin/temp/view3.html");
		}
	}
	
	

	/**
	 * 访问初页模板
	 */
	@Before(WxInterceptor.class)
	public void editcy() {
		String type = getPara("type");
		String fromuser = getPara("fromuser");
		String id=getPara("id");
		List<Record> mblist = Db.find("select * from wx_mb where id=?", type);
		List<Record> mbsxlist = Db.find(
				"select * from wx_mbsx where type='img'  and lbid=?", type);
		String urls = url + "wxContent/editcy?id="+id+"&type=" + type + "&fromuser="+ fromuser;
		String urla="";
		if(url.endsWith("/")){
			urla=url.substring(0,url.length()-1)+getAttr("wxurls").toString();
		}
		else {
			urla=url+getAttr("wxurls").toString();
		}
	///	System.out.println("urls++++++++++++++++++"+urls);

		System.out.println("urla++++++++++++++++++"+urls);

		Map map = CheckJs.setsign(urls);
		setAttr("appId", AppId);
		setAttr("timestamp", map.get("timestamp"));
		setAttr("nonceStr", map.get("nonceStr"));
		setAttr("signature", map.get("signature"));
		setAttr("mbsxlist", mbsxlist);
		setAttr("mblist", mblist);
		setAttr("fromuser", fromuser);
		setAttr("contentid", id);
		setAttr("argu", "edit");
		render("/WEB-INF/view/weixin/temp/cy.html");
	}
	
	/**
	 * 访问初页模板
	 */
	@Before(WxInterceptor.class)
	public void editcys() {
		String type = getPara("type");
		String fromuser = getPara("fromuser");
		String id=getPara("id");
		List<Record> mblist = Db.find("select * from wx_mb where id=?", type);
		List<Record> mbsxlist = Db.find(
				"select * from wx_mbsx where type='img'  and lbid=?", type);
		String urls = url + "wxContent/editcys?id="+id+"&type=" + type + "&fromuser="+ fromuser;
		String urla="";
		if(url.endsWith("/")){
			urla=url.substring(0,url.length()-1)+getAttr("wxurls").toString();
		}
		else {
			urla=url+getAttr("wxurls").toString();
		}
	///	System.out.println("urls++++++++++++++++++"+urls);

		System.out.println("urla++++++++++++++++++"+urls);

		Map map = CheckJs.setsign(urls);
		setAttr("appId", AppId);
		setAttr("timestamp", map.get("timestamp"));
		setAttr("nonceStr", map.get("nonceStr"));
		setAttr("signature", map.get("signature"));
		setAttr("mbsxlist", mbsxlist);
		setAttr("mblist", mblist);
		setAttr("fromuser", fromuser);
		setAttr("contentid", id);
		setAttr("argu", "edit");
		render("/WEB-INF/view/weixin/temp/cy.html");
	}
	

	public void edit() {
		String id = getPara("id");
		List<Record> newlist = WxContent.dao.findAlls("       id=  '" + id
				+ "'", "");
		setAttr("newlist", newlist);
		render("/WEB-INF/view/weixin/temp/edit.html");
	}

	public void more() {
		String fromuser = getPara("fromuser");
		List<Record> newlist = WxContent.dao.findAlls("       fromuser=  '"
				+ fromuser + "'", "");
		setAttr("newlist", newlist);

		render("/WEB-INF/view/weixin/temp/more.html");

	}

	/**
	 * save
	 * 
	 * @param
	 * @return
	 */
	public void save() {
		if (getModel(WxContent.class).save()) {
			renderJson("保存成功");
		} else {
			renderJson("保存失败");
		}
	}
	/**
	 * save
	 * 初页模板保存
	 * @param
	 * @return
	 */
	public void saveCy() {
		String contentid = getPara("contentid");
		String type = getPara("lbid");
		String mbsxid = getPara("mbsxid");
		String fromuser = getPara("fromuser");
		String nr = getPara("nr");
		String url=getPara("url");
		String color=getPara("color");
		String mbbh=getPara("mbbh");
		String tx=getPara("tx");
		List<Record> mblist = Db.find(
				"select * from  wx_usermbsx where mbsxid =? and  contentid=?",
				mbsxid, contentid);
		Record ss = new Record();
		boolean flg = false;
		ss.set("lbid", type).set("mbsxid", mbsxid)
				.set("contentid",contentid).set("style", fromuser)
				.set("nr", nr).set("url", url).set("color", color).set("mbbh",mbbh).set("tx",tx);
		if (mblist.size() > 0) {
			if(StringKit.isBlank(url)){
				ss.remove("url");
			}
			if(StringKit.isBlank(color)){
				ss.remove("color");
			}
			if(StringKit.isBlank(nr)){
				ss.remove("nr");
			}
			if(StringKit.isBlank(tx)){
				ss.remove("tx");
			}
			ss.set("id", mblist.get(0).get("id"));
			flg = Db.update("wx_usermbsx", ss);
		} else {
			flg = Db.save("wx_usermbsx", ss);
		}
		 if (flg) {
		 renderText("1");
		 } else {
		 renderText("0");
		 }
	}
	
	public void saveform(){
		String content=getPara("content");
		String type=getPara("type");
		String title=getPara("title");
		String picurl=getPara("picurl");
		String fromuser=getPara("fromuser");
		String yxbz=getPara("yxbz");
		Record  xx= new Record();
		xx.set("content",content).set("type",type).set("picurl",picurl)
		.set("fromuser",fromuser).set("yxbz",yxbz).set("title",title);
		boolean flg=Db.save("wx_content",xx);
		if(flg){
			renderText(xx.get("id")+"");
		}else{
			renderText("0");
		}
	}
	
	/**
	 * save
	 * 初页模板保存
	 * @param
	 * @return
	 */
	public void saveCyBYuser() {
		String[] musicurl=getParaValues("musicurl");
		String btmc=getPara("btmc");
		String type = getPara("lbid");
		String fromuser = getPara("fromuser");
		String[] nr = getParaValues("nr");
		String[] url=getParaValues("url");
		String[] color=getParaValues("color");
		String[] mbbh=getParaValues("mbbh");
		String[] tx=getParaValues("tx");
		// 信息保存
		Record xx=new Record();
		xx.set("type", type).set("fromuser", fromuser).set("yxbz", "1")
		.set("title",btmc).set("picurl", url[0]);
		Db.save("wx_content", xx);
	
		String sql="insert into wx_usermbsx(lbid,musicurl,nr,url,color,mbbh,tx,contentid)" +
				" values('"+type+"',?,?,?,?,?,?,'"+xx.get("id")+"') ";
		//信息内容保存。
		   int count = url.length;
        Object[][] params = new Object[count][6];
        for(int i=0;i<count;i++){
            params[i][0]=musicurl[i];
            params[i][1]=nr[i];
            params[i][2]=url[i];
            params[i][3]=color[i];
            params[i][4]=mbbh[i];
            params[i][5]=tx[i];
        }
		int[] j=Db.batch(sql,  params, count);
//		Record ss = new Record();
//		boolean flg = false;
//		ss.set("lbid", type).set("contentid",xx.get("id")).set("style", fromuser)
//				.set("nr", nr).set("url", url).set("color", color).set("mbbh",mbbh).set("tx",tx);
//			flg = Db.save("wx_usermbsx", ss);
		 if (j.length>0) {
		 renderText(xx.get("id")+"");
		 } else {
		 renderText("0");
		 }
	}
	public void getimg(){
		String mediaId=getPara("medaid");
		String file = MediaApi.getMedia( mediaId,"");
		renderText(file);
	}
	
	public void getvoice(){
		String mediaId=getPara("medaid");
		String file = MediaApi.getMedia( mediaId,"");
		
		String filea = "";
		System.out.println(PathKit.getWebRootPath() + file);
		try {
			filea = AmrToMp3.armtomp3(
					PathKit.getWebRootPath() + file,
					PathKit.getWebRootPath()
							+ file.substring(0, file.length() - 4) + ".mp3");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		file = file.substring(0, file.length() - 4) + ".mp3";
		System.out.println("filea===============" + filea);
		renderText(file);
//		String mediaId=getPara("medaid");
//		String contentid=getPara("contentid");
//		Record xx =new Record();
//		String file = MediaApi.getMedia( mediaId,"");
//		xx.set("id", contentid).set("musicurl", file);
//		boolean flg=Db.update("wx_content",xx);
//		if(flg){
//			renderText(file);
//		}else{
//			renderText("0");
//		}
	}
	
	public void updateurl(){
		String contentid=getPara("contentid");
		Record xx =new Record();
		xx.set("id", contentid).set("picurl", "");
		Db.update("wx_content",xx);
		renderText("1");
	}
	public void updattitle(){
		String contentid=getPara("contentid");
		String title="";
		Record xx =new Record();
		xx.set("id", contentid).set("title", title);
		Db.update("wx_content",xx);
		renderText("1");
	}
	
	public void update() {
		String conn = getPara("wxContent.content");
		System.out.println("======" + conn);
		if (getModel(WxContent.class).update()) {
			renderJson("修改成功");
		} else {
			renderJson("修改失败");
		}
	}

	public void delete() {

		if (WxContent.dao.deleteById(getPara("id"))) {
			renderJson("删除成功！");
		} else {
			renderJson("删除失败！");
		}
	}
	//查看
	public void view(){
		String id=getPara(0);
		String title="";
		String descContent="";
		String pic="";
		String gkzt="";
		String urls = "";
		String  musicurl="";
		List<Record> newlist = WxContent.dao.findAlls("       id=  '" + id
				+ "'", "");
		String type=newlist.get(0).get("type");
		List<Record> mblist = Db.find("Select *  from wx_mb where id ='" + type
				+ "'  order by dsporder");
		List<Record> list=Db.find("select * from  wx_usermbsx  where contentid=?",newlist.get(0).get("id"));
//		List<Record> mbsxlist=Db.find("select * from wx_mbsx where type='img'  and lbid=?",type);
		String yds = newlist.get(0).getStr("yds");
		if (!StringKit.notBlank(yds)) {
			yds = "0";
		}
		int s = Integer.parseInt(yds) + 1;
		Db.update(" update wx_content set yds=" + s + "  where id ='" + id+ "'");
		if (newlist.size() > 0) {
			type = newlist.get(0).get("type");
			title = newlist.get(0).get("title");
			gkzt = newlist.get(0).get("gkzt");
			descContent = "我的朋友圈...";
			musicurl= newlist.get(0).get("musicurl");
		
			if (newlist.get(0).get("picurl") != null) {
				if (url.endsWith("/")) {
					pic = url.substring(0,url.length()-1) + newlist.get(0).get("picurl");
				}
			}
		}
		String mblx=mblist.get(0).getStr("mblx");

		setAttr("gkzt", gkzt);
		setAttr("pic", pic);
		setAttr("title", title);
		setAttr("viewmb",mblist.get(0).getStr("viewmb"));
		setAttr("descContent", descContent);
//		urls = mblist.get(0).get("mburl");
//		String mblx = mblist.get(0).get("mblx");
//		if (urls != null && !urls.substring(0, 1).equals("/")) {
//			urls = "/" + urls;
//		}
		setAttr("bjzt", "bjzt");
		setAttr("mblist", mblist);
		setAttr("contlist",list);
		setAttr("argu","view");
		setAttr("newlist",newlist);
		String viewmb="0";
		String viewurls="";
		viewmb=mblist.get(0).getStr("viewmb");
		viewurls=mblist.get(0).get("mburl");
		if (viewurls != null && !viewurls.substring(0, 1).equals("/")) {
			viewurls = "/" + viewurls;
		}
//		setAttr("mbsxlist",mbsxlist);
		setAttr("id",id);
		setAttr("AppId", AppId);
		setAttr("musicurl",musicurl);
		if(mblx.equals("1")){
			if(StringKit.notBlank(viewmb) ){
				if(viewmb.equals("1")){
					render("/WEB-INF/view/weixin/temp/"+viewurls);
				}
			}else {
				render("/WEB-INF/view/weixin/temp/cyview.html");
			}
		}else {
			render("/WEB-INF/view/weixin/temp/tempview.html");
		}
	}

	/**
	 * 去除str中的所有HTML代码
	 * 
	 * @param str
	 * @return str中的非HTML代码部分
	 */
	public static String getAbStract(String str) {
		String regexpForHtml = "<([^>]*)>";
		str = str.replaceAll(regexpForHtml, "");
		str = str.replaceAll("<", "");
		str = str.replaceAll(">", "");
		str = str.replaceAll("\r\n|\r|\n|\n\r", "");
		str = str.replaceAll("\\s*|\t|\r|\n", "");

		return str;
	}
	public void del(){
		String id=getPara("id");
		boolean flag=Db.deleteById("wx_content", id);
		Db.update("delete from wx_usermbsx where contentid ='"+id+"'");
		if(flag){
			renderText("1");
		}else{
			renderText("0");
		}
	}
}
